<template>
    <div class="todo-item-loop"> 
        <div class="todo-item">
            <div>
                <input type="checkbox" 
                    v-model="theTodo.completed" 
                    v-if="!theTodo.editing"
                    @change="$emit('statusChange',theTodo)">
                <span class="todo-title" 
                    v-if="!theTodo.editing" 
                    @dblclick="$emit('editTodo',theTodo)" 
                    :class="{completed_cls: theTodo.completed}">
                    {{ theTodo.title }}
                </span>
                <input type="text" class="todo-title-edit" 
                    v-else 
                    v-model="theTodo.title" 
                    @blur="$emit('cancelEditing',theTodo)"
                    @keyup.esc="$emit('cancelEditing',theTodo)" 
                    @keyup.enter="$emit('doneEditing',theTodo)" 
                    v-focus>
            </div>
            
            <div class="remove-todo-item" 
                v-if="!theTodo.editing" 
                @click="$emit('remove','delete one',theTodo)">
                &times;
            </div>
        </div>
        <div v-if="theTodo.editing" class="edit-tip">
            * 回车 - 保存，ESC - 取消
        </div>
    </div>
</template>

<script>
export default {
    name: 'todo-item',
    props: {
        todo: {
            type: Object,
            required: true
        }
    },
    directives: {
        focus: {
            // 指令的定义
            inserted: function (el) {
                el.focus()
            }
        }
    },
    watch: {
        todo: {
            handler: function(newTodo){
                this.theTodo = JSON.parse(JSON.stringify(newTodo))
            },
            deep: true
        },
    },
    data(){
        return {
            theTodo: JSON.parse(JSON.stringify(this.todo))
        }
    },
    methods: {
        
    }
}
</script>

<style scoped>
.todo-item{
    margin-top: 8px;
    display: flex;
    justify-content: space-between;
}
.todo-title{
    cursor: pointer;
}
.remove-todo-item{
    cursor: pointer;
    color: #999;
}
.remove-todo-item:hover{
    color: red;
}
.completed_cls{
    text-decoration: line-through;
    color: gray;
    cursor: default;
    user-select: none;
}
.todo-title-edit{
    width: 500px;
    margin-left: 24px;
    /* padding: 10px 18px; */
}
</style>

